<!--
 * @Author: DT1604\ZPL zhoupeili@dpc.com.cn
 * @Date: 2022-05-25 14:21:01
 * @LastEditors: DT1604\ZPL zhoupeili@dpc.com.cn
 * @LastEditTime: 2022-08-22 17:55:21
 * @FilePath: \energy-om-platform\src\views\cabint\operate.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="operate">
    <el-form ref="form" :model="form" label-width="170px" :rules="rules">
      <el-form-item label="已选设备" v-if="updateType != 'condition'">
        <el-tag class="tag_one" v-for="(tag, inx) in equipList" :key="inx">
          {{ tag.code }}
        </el-tag>
      </el-form-item>
      <el-form-item label="升级类型" prop="type">
        <el-select
          v-model="form.type"
          placeholder="请选择升级类型"
          style="width: 100%"
        >
          <el-option
            v-for="(item, index) in enums.SOFTWARE_UPGRADE_TYPE"
            :key="index"
            :label="item.label"
            :value="item.code"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="选择软件版本" prop="softwareVersionId">
        <el-select
          v-model="form.softwareVersionId"
          placeholder="请选择软件版本"
          style="width: 100%"
        >
          <el-option
            v-for="(item, index) in softList"
            :key="index"
            :label="item.filename"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="每次升级个数"
        v-if="updateType != 'single'"
        prop="count"
        class="flexLayout"
      >
        <el-input-number
          style="width: 100%"
          :min="1"
          :max="maxUpdateNum"
          :step="1"
          step-strictly
          controls-position="right"
          placeholder="请输入升级个数"
          v-model="form.count"
        ></el-input-number>
      </el-form-item>
      <p class="tips-title" v-if="updateType != 'single'">
        <i class="el-icon-info"></i><span> 范围：1~10</span>
      </p>
      <el-form-item
        label="升级间隔（分钟）"
        v-if="updateType != 'single'"
        prop="interval"
        class="flexLayout"
      >
        <el-input-number
          style="width: 100%"
          :min="0"
          :max="60"
          :step="1"
          step-strictly
          controls-position="right"
          placeholder="请输入升级间隔"
          v-model="form.interval"
        >
        </el-input-number>
      </el-form-item>
      <p class="tips-title" v-if="updateType != 'single'">
        <i class="el-icon-info"></i>
        <span>
          范围：0~60，为0时升级个数为执行线程数；非0时按照间隔执行，每次执行线程数为升级个数</span
        >
      </p>

      <el-form-item
        label="查询版本间隔（分钟）"
        v-if="updateType != 'single'"
        prop="queryVersionDelay"
        class="flexLayout"
      >
        <el-input-number
          style="width: 100%"
          :min="0"
          :max="60"
          :step="1"
          step-strictly
          controls-position="right"
          placeholder="请输入查询版本间隔"
          v-model="form.queryVersionDelay"
        >
        </el-input-number>
      </el-form-item>
      <p class="tips-title" v-if="updateType != 'single'">
        <i class="el-icon-info"></i>
        <span> 范围：0~60，为0时设备返回结果立即查询版本，非0时延迟执行。</span>
      </p>
      <el-form-item class="dialog-footer">
        <el-button @click="resetForm('form')">取消</el-button>
        <el-button
          type="primary"
          @click="submitForm('form')"
          :loading="btnLoading"
          >确定</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { softversion, equipUpdate } from "@/api/cabint";

export default {
  props: {
    equipList: {
      default: [],
      type: Array,
    },
    updateDialogVisible: {
      default: true,
      type: Boolean,
    },
    // 设备类型
    equipType: {
      type: String,
      default: "",
    },
    // 升级类型：单个还是批量
    updateType: {
      type: String,
      default: "",
    },
    // 批量（条件）搜索条件参数
    conditionForm: {
      type: Object,
      default: {},
    },
  },
  data() {
    return {
      form: {
        softwareVersionId: "",
        type: "",
        count: "", //升级个数
        interval: "", //间隔
        queryVersionDelay: "", //查询版本
      },
      rules: {
        softwareVersionId: [
          { required: true, message: "请选择软件版本", trigger: "change" },
        ],
        type: [
          { required: true, message: "请选择升级类型", trigger: "change" },
        ],
        count: [
          { required: true, message: "请输入每次升级个数", trigger: "blur" },
        ],
        interval: [
          { required: true, message: "请输入升级间隔", trigger: "blur" },
        ],
        queryVersionDelay: [
          { required: true, message: "请输入查询版本间隔", trigger: "blur" },
        ],
      },
      softList: [],
      btnLoading: false, //按钮loading
    };
  },
  computed: {
    ...mapGetters(["enums"]),
    maxUpdateNum() {
      return this.updateType == "batch"
        ? this.equipList.length < 10
          ? this.equipList.length
          : 10
        : 10;
    },
  },

  watch: {
    updateDialogVisible: {
      handler(newVal, oldVal) {
        if (!newVal) {
          this.resetData();
        }
      },
      immediate: true,
    },
    equipType: {
      handler(newVal, oldVal) {
        if (newVal) {
          this.getSoftList();
        }
      },
      immediate: true,
    },
  },

  methods: {
    resetData() {
      this.resetForm("form");
      this.btnLoading = false;
    },
    // 获取软件版本集合
    async getSoftList() {
      let res = await softversion({ equipmentType: this.equipType });
      this.softList = res.data;
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.isDoUpdate();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.form = {
        softwareVersionId: "",
        type: "",
        count: "", //升级个数
        interval: "", //间隔
        queryVersionDelay: "", //查询版本
      };
      this.emitClose();
    },
    // 通知关闭弹框
    emitClose() {
      this.$emit("closeDialog");
    },

    // 升级
    doUpdate() {
      this.btnLoading = true;
      if (this.updateType != "condition") {
        //批量（选中）或单个升级
        let codes = this.equipList.map((item) => {
          return item.code;
        });

        let params = {};

        params =
          this.updateType == "batch"
            ? Object.assign(this.form, {
                equipmentCodes: codes.join(","),
              })
            : {
                equipmentCode: codes.join(","),
                softwareVersionId: this.form.softwareVersionId,
                type: this.form.type,
              };
        let url = this.updateType == "batch" ? "/batch/insert" : "/insert";
        equipUpdate(url, "post", params)
          .then((res) => {
            if (res.code == 200) {
              this.emitClose();
              this.$message({
                message: res.message,
                type: "success",
              });
            }
          })
          .finally((complete) => {
            this.btnLoading = false;
          });
      } else {
        //批量（条件）
        this.doConditionUpdate();
      }
    },
    doConditionUpdate() {
      if (this.conditionForm.codes && this.conditionForm.codes.length == 1) {
        this.conditionForm.code = this.conditionForm.codes[0];
        delete this.conditionForm.codes;
      }
      equipUpdate(
        "/batch/insert/condition",
        "post",
        Object.assign({ queryParam: this.conditionForm }, this.form),
        1
      )
        .then((res) => {
          if (res.code == 200) {
            this.emitClose();
            this.$message({
              message: res.message,
              type: "success",
            });
          }
        })
        .finally(() => (this.conditionLoading = false));
    },
    isDoUpdate() {
      let msg =
        this.updateType == "condition"
          ? `确定要按查询条件批量升级${
              this.equipType == "CHARGING_CABINET" ? "充电柜" : "换电柜"
            }吗?`
          : `是否确认要升级已选${
              this.equipType == "CHARGING_CABINET" ? "充电柜" : "换电柜"
            }?`;
      this.$confirm(msg, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.doUpdate();
      });
    },
  },
};
</script>
<style scoped lang="scss">
@import "@/assets/css/scss.scss";

.tag_one {
  margin-right: 10px;
}
.dialog-footer {
  text-align: right;
}
.el-icon-question {
  font-size: 16px;
  color: #f56c6c;
  position: relative;
  bottom: -1px;
}
.flexLayout {
  ::v-deep .el-form-item__content {
    @include flexLayout(center, flex-start);
  }
}
.tips-title {
  margin-left: 180px;
  margin-top: -16px;
  color: #817f7f;
  font-size: 14px;
  @include flexLayout(flex-start, flex-start);
  i {
    margin-right: 4px;
    color: #eaad52;
  }
}
</style>
